<route lang="json5" type="page">
{
  layout: 'default',
  style: {
    navigationBarTitleText: '我的订单',
  },
}
</route>

<template>
  <view class="order-page">
    <!-- 顶部状态栏 -->
    <view class="status-bar">
      <view
        v-for="(item, index) in statusList"
        :key="index"
        :class="['status-item', { active: currentStatus === index }]"
        @click="getType(item)"
      >
        {{ item }}
      </view>
    </view>

    <wd-search
      v-model="searchValue"
      placeholder="请输入订单号"
      cancel-txt="搜索"
      @cancel="searchCancel"
    />

    <!-- 订单列表 -->
    <view class="order-list">
      <view
        class="order-item"
        v-for="(order, index) in orders.records"
        :key="index"
        @click="goOrderDetail(order)"
      >
        <view class="order-code">订单编码： {{ order.orderCode }}</view>
        <view class="order-header">
          <view class="order-date">{{ order.createTime }}</view>
          <view class="order-status">{{ order.orderStatus }}</view>
        </view>

        <view class="product-list">
          <view class="product-item" v-for="(product, pIndex) in order.details" :key="pIndex">
            <wd-img :src="product.mainPic" width="80" height="80"></wd-img>
            <view class="product-info">
              <view class="product-title">{{ product.productName }}</view>
              <view class="product-spec">{{ product.l2Type }}</view>
            </view>
            <view class="product-price">
              <view class="price">¥{{ product.productPrice }}</view>
              <view class="count">×{{ product.orderQuantity }}</view>
            </view>
          </view>
        </view>

        <view class="order-footer">
          <view class="total">
            共{{ order.totalNum }}件({{ orders.detailNum }}种)商品 实付：¥{{ order.totalAmount }}
          </view>
          <view
            style="display: flex; align-items: center; justify-content: flex-end; margin-top: 10px"
          >
            <view
              class="action-btn"
              v-for="(item, index) in order.orderActions"
              :key="index"
              @click.stop="handleAction(order, item)"
            >
              {{ item }}
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import { onLoad, onReachBottom } from '@dcloudio/uni-app'
import { getOrderListByPage, preUnifieAppletdorder, getReciveOrder } from '@/service/order'
import { useProfileStore } from '@/store'
import { useShopcartStore } from '@/store/shopcart'
import { storeToRefs } from 'pinia'
import { useMessage } from 'wot-design-uni'
const message = useMessage()
const profileStore = useProfileStore()
const shopcartStore = useShopcartStore()

const { profileInfo, chargeStore } = storeToRefs(profileStore)
const { shopcartTotal } = storeToRefs(shopcartStore)

const statusList = ['全部', '待支付', '待审核', '待发货', '待收货']
const currentStatus = ref(0)
const num = ref(0)
const searchValue = ref('')
const type = ref('')
const orders = ref([])

const goOrderDetail = (order: any) => {
  uni.navigateTo({
    url: `/pages/order-detail/orderDetail?orderCode=${order.orderCode}`,
  })
}

const handleAction = async (order: any, action: string) => {
  if (action === '查看物流') {
    uni.navigateTo({
      url: `/pages/logistics-details/logistics-details?orderCode=${order.orderCode}`,
    })
  }
  if (action === '申请售后') {
    console.log(order)
    uni.navigateTo({
      url: `/pages/return-goods-order/return-goods-order?order=${JSON.stringify(order)}`,
    })
  }
  if (action === '去支付') {
    handlePay(order.orderCode)
  }
  if (action === '收货') {
    confirm(order.orderCode)
  }
}
function confirm(orderCode: string) {
  message
    .confirm({
      msg: '为了保障您的售后权益，请收到商品确认无误后再确认收货',
      title: '确认收到货了吗？',
    })
    .then(() => {
      getReciveOrder({ orderCode }).then((res) => {
        console.log(res)
        if (res.code === 200) {
          orders.value = []
          pageNo.value = 1
          uni.showToast({
            title: res.message,
            icon: 'none',
          })
          initOrderList()
        }
      })
      console.log('点击了确定按钮')
    })
    .catch(() => {
      console.log('点击了取消按钮')
    })
}
const handlePay = async (orderCode: string) => {
  try {
    const response = await preUnifieAppletdorder({ orderCode })
    if (response.success) {
      uni.navigateToMiniProgram({
        appId: response.result.useAppid,
        path: response.result.appletUrl,
        success(res) {
          // 打开成功
          uni.showToast({
            title: res,
            icon: 'none',
          })
        },
        fail: (fail) => {
          uni.showToast({
            title: fail,
            icon: 'none',
          })
        },
      })
    } else {
      uni.showToast({
        title: response.message,
        icon: 'none',
      })
    }
  } catch (e) {}
}

const searchCancel = () => {
  pageNo.value = 1
  orders.value = []
  console.log(searchValue.value)
  initOrderList()
}
// 根据类型获取状态
const getType = (data: string) => {
  // 清空页码
  orders.value = []
  pageNo.value = 1
  type.value = data
  if (data === '待支付') {
    currentStatus.value = 1
  } else if (data === '全部') {
    currentStatus.value = 0
  } else if (data === '待审核') {
    currentStatus.value = 2
  } else if (data === '待发货') {
    currentStatus.value = 3
  } else if (data === '待收货') {
    currentStatus.value = 4
  } else {
    type.value = '全部'
    currentStatus.value = 0
  }

  initOrderList()
}
const initOrderList = () => {
  console.log(`type.value`, type.value)
  getOrderListByPage({
    listType: type.value || '全部',
    pageNo: 1,
    pageSize: 10,
    storeCode: chargeStore.value.storeCode,
    orderCode: searchValue.value,
  }).then((res) => {
    if (res.code === 200) {
      orders.value = res.result
    }
  })
}

const getOrderList = (pageNo: any, pageSize: any) => {
  console.log(`type.value`, type.value)
  getOrderListByPage({
    listType: type.value || '全部',
    pageNo,
    pageSize,
    storeCode: chargeStore.value.storeCode,
    orderCode: searchValue.value,
  }).then((res) => {
    if (res.code === 200) {
      if (res.result.records.length > 0) {
        orders.value.records.push(...res.result.records)
      } else {
        console.log('暂无多的数据')

        uni.showToast({
          title: '暂无多的数据',
          icon: 'none',
        })
      }
    }
  })
}
onLoad((options) => {
  type.value = options.type || '全部'
})
onShow(() => {
  getType(type.value)
})

const pageNo = ref(1)
const pageSize = ref(10)
onReachBottom(async () => {
  console.log(`触底`)
  pageNo.value = pageNo.value + 1
  getOrderList(pageNo.value, pageSize.value)
})
</script>

<style lang="scss" scoped>
.order-page {
  min-height: 100vh;
  background: #f5f5f5;
}

.status-bar {
  position: sticky;
  top: 0;
  z-index: 10;
  display: flex;
  padding: 10px 0;
  background: #fff;

  .status-item {
    position: relative;
    flex: 1;
    font-size: 14px;
    color: #333;
    text-align: center;

    &.active {
      color: #2979ff;
      &::after {
        position: absolute;
        bottom: -10px;
        left: 50%;
        width: 20px;
        height: 2px;
        content: '';
        background: #2979ff;
        transform: translateX(-50%);
      }
    }
  }
}

.order-list {
  padding: 10px;

  .order-item {
    padding: 15px;
    margin-bottom: 10px;
    background: #fff;
    border-radius: 8px;

    .order-code {
      font-size: 14px;
      color: #666;
    }
    .order-header {
      display: flex;
      justify-content: space-between;
      padding-bottom: 10px;
      border-bottom: 1px solid #eee;

      .order-date {
        font-size: 14px;
        color: #666;
      }

      .order-status {
        font-size: 14px;
        color: #ff0000;
      }
    }

    .product-list {
      max-height: 200px;
      overflow: scroll;
      .product-item {
        display: flex;
        padding: 10px 0;

        .product-img {
          width: 80px;
          height: 80px;
          background: #ff0000;
          border-radius: 4px;
        }

        .product-info {
          flex: 1;
          padding: 0 10px;

          .product-title {
            margin-bottom: 5px;
            font-size: 14px;
            color: #333;
          }

          .product-spec {
            font-size: 12px;
            color: #999;
          }
        }

        .product-price {
          text-align: right;

          .price {
            font-size: 14px;
            color: #ff0000;
          }

          .count {
            margin-top: 5px;
            font-size: 12px;
            color: #999;
          }
        }
      }
    }

    .order-footer {
      padding-top: 10px;
      border-top: 1px solid #eee;

      .total {
        font-size: 14px;
        color: #333;
      }

      .action-btn {
        padding: 5px 15px;
        margin-left: 10px;
        font-size: 14px;
        color: #fff;
        background: #ff0000;
        border-radius: 15px;
      }
    }
  }
}
</style>
